import React from "react";

type OptionT = {
  value: string;
  label: string;
};

interface Props {
  options: OptionT[];
  value: string[];
  onChange: (value: string[]) => void;
}

const MultiSelect: React.FC<Props> = ({
  options = [],
  value,
  onChange,
}: Props) => {
  console.log(options);
  console.log(value);

  return (
    // defaultValue和value属性只能留一个，决定它是受控组件还是非受控组件
    <select
      value={value}
      multiple={true}
      onChange={(e) => {
        console.log(e.target.value);
        const index = value.findIndex((item) => item == e.target.value);
        if (index > 0) {
          value.splice(index, 1);
        } else {
          value.push(e.target.value);
        }
        onChange(value);
      }}
    >
      {options.map((option: OptionT) => {
        return (
          <option value={option.value} key={option.value}>
            {option.label}
          </option>
        );
      })}
    </select>
  );
};

export default MultiSelect;
